package fisio.control;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fisio.dao.FotoDAO;
import fisio.dao.PacienteDAO;
import fisio.global.Const;
import fisio.model.Foto;
import fisio.model.Paciente;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FotoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    @Override
	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    	try {
	    	int id_f = Integer.parseInt(req.getParameter("id"));
	    	Foto f = FotoDAO.getFoto(id_f);
	    	
	    	InputStream in = f.getFoto();
	    	
	    	res.reset();
	    	res.setContentType("image/png");
	    	
	    	int size = 0;
	    	byte[] barr = new byte[1048576];
	    	OutputStream out = res.getOutputStream();
	    	
	    	while ((size = in.read(barr)) != -1) {
	    		out.write(barr, 0, size);
	    	}
    	} catch (Exception ex) {
    		res.sendError(500);
    	}
	}
    
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    	String rel = req.getParameter("rel");
    	int id = Integer.parseInt(req.getParameter("id"));
    	
    	if (rel.equals("paciente")) {
			ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
			List fileItemsList = null;
			try {
				fileItemsList = servletFileUpload.parseRequest(req);
			} catch (FileUploadException ex) {
				throw new ServletException(ex);
			}
			
			Iterator it = fileItemsList.iterator();
			
			if (it.hasNext()) {
				FileItem fileItem = (FileItem)it.next();
				
				if (fileItem.getSize() > 0) {
					Paciente p = PacienteDAO.getPaciente(id);
					p.setFoto(FotoDAO.insertFoto(new Foto(fileItem.getInputStream(), fileItem.getSize())));
					PacienteDAO.editPaciente(p);
				}
			}
			res.sendRedirect(Const.SERVLET_PACIENTE + "?op=exibir&id=" + id);
    	} else {
    		throw new ServletException("KABOOM BABY!");
    	}
    }
}